USE [Test_Events_Temp]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetIncidentsByCompanyIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spGetIncidentsByCompanyIds]
GO


CREATE PROCEDURE [dbo].[spGetIncidentsByCompanyIds]
	@CompanyIds NVARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @XML XML
	SET @XML = CONVERT(XML, @CompanyIds, 1)

	DECLARE @SelectedCompanies TABLE
	(
		Id uniqueidentifier
	)
	INSERT INTO @SelectedCompanies
	SELECT TID.id.value('.','uniqueidentifier') AS Id
	FROM @XML.nodes('/CompanyIds') AS T(c) outer apply T.c.nodes('Id') as TID(id)

	SELECT PublishedIncidents.[Id]
		  ,[CompanyId]
		  ,[EventIndicatorId]
		  ,[EventIndicatorName]
		  ,[IncidentId]
		  ,[Type]
		  ,[Name]
		  ,[Summary]
		  ,[Analysis]
		  ,[MainTag]
		  ,[HasSupplyChainSpecialTag]
		  ,[Source]
		  ,[IncidentDate]
		  ,[LocationAddress]
		  ,[LocationLatitude]
		  ,[LocationLongitude]
		  ,[ImpactScore]
		  ,[RiskScore]
		  ,[LastUpdated]
		  ,[Timestamp]
	FROM [dbo].[PublishedIncidents] AS PublishedIncidents
	INNER JOIN @SelectedCompanies AS SelectedCompanies ON SelectedCompanies.Id = PublishedIncidents.CompanyId
	 
END
GO


